package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

@WebServlet("/findAll")
public class EmpListServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.println("<!DOCTYPE html>");
        out.println("<html lang=\"en\">");
        out.println("<head>");
        out.println("    <meta charset=\"UTF-8\">");
        out.println("    <title>员工列表</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>员工列表</h1>");
        out.println("<a href=\"showAddEmp\">添加员工</a>");
        out.println("<hr>");
        out.println("<table border=\"1\">");
        out.println("    <tr>");
        out.println("        <th>编号</th>");
        out.println("        <th>姓名</th>");
        out.println("        <th>工资</th>");
        out.println("        <th>操作</th>");
        out.println("    </tr>");

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            // 查询数据库中所有员工信息
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8", "root", "root");
            String sql = new StringBuffer()
                    .append(" select id,name,salary ")
                    .append(" from t_emp ")
                    .toString();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                out.println("    <tr>");
                out.println("        <td>" + rs.getInt("id") + "</td>");
                out.println("        <td>" + rs.getString("name") + "</td>");
                out.println("        <td>" + rs.getDouble("salary") + "</td>");
                out.println("        <td>");
                out.println("            <a href=\""+req.getContextPath()+"/findById?id="+rs.getInt("id")+"\">修改</a>");
                out.println("            <a href=\""+req.getContextPath()+"/deleteEmp?id="+rs.getInt("id")+"\" onclick=\"return confirm('是否确认删除')\">删除</a>");
                out.println("        </td>");
                out.println("    </tr>");
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


        out.println("</table>");
        out.println("</body>");
        out.println("</html>");
    }
}
